﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BusinessClass.Business;


namespace BusinessClass.Business
{
    /// <summary>
    /// 工作流程点，返回值 第一个是工作流程点名称，第二个是返回码
    /// </summary>
    /// <returns></returns>
    public delegate void Work(out string workName, out ErrorCodeList discription);
    public abstract class Worker
    {
        /// <summary>
        /// 接口名称
        /// </summary>
        /// <returns></returns>
        public abstract string GetConcreteWorkerName();
        /// <summary>
        /// 工作流程点数组，会从第一个执行到最后一个，其中一个失败就返回。
        /// </summary>
        public abstract List<Work> GetWorkSequence();
        /// <summary>
        /// 可能是失败停止，也可能是成功执行完所有流程.子类负责返回结果给客户端
        /// 返回值 第一个是工作流程点名称，第二个是返回码
        /// </summary>
        /// <param name="discription"></param>
        public abstract void WhenStopWorking(string workName, ErrorCodeList discription);
        protected ILogger Logger;
        public Worker()
        {
            Logger = new FileLogger();
        }
        private void Write(string title, string content)
        {
            Logger.Write(GetConcreteWorkerName() + "\r\n" + title + content);
        }


        public virtual void Do()
        {
            try
            {
                int index = 1; // 在日志中方便显示步骤
                var WorkSequence = GetWorkSequence();
                foreach (var work in WorkSequence)
                {
                    string workName;
                    ErrorCodeList discription;
                    work(out workName, out discription);
                    Write(index.ToString() + ":" + workName, discription.ToString());
                    index++;
                    if (discription != ErrorCodeList.SUCCESS)  //半路执行点失败时
                    {
                        WhenStopWorking(workName, discription);
                        return;
                    }
                }
                WhenStopWorking("流程执行停止", ErrorCodeList.SUCCESS);
            }
            catch (Exception err)
            {
                WhenStopWorking("执行异常", ErrorCodeList.FAILED);
                Write("执行异常", err.Message);
            }
        }
    }
}